using System.Collections.Generic;
using System.Configuration;
using Less.Core;
using Less.Core.Model;

namespace Less.DAL
{
    internal class RolesDAL : GenericDAL<Role>
    {
        internal RolesDAL(IDatabase database)
            : base(database,"Roles")
        {
        }

        internal RolesDAL()
            : base(new Database(LessDatabaseUtils.LessConnectionStringName),"Roles")
        {
        }
        
        public string SQLSelectRolesByUserName
        {
            get
            {
                string name = ConfigurationManager.AppSettings["RolesDAL.SelectRolesByUserNameSQL"];
                if (name == null)
                {
                    name = @"SELECT r.* FROM Roles r INNER JOIN UsersRoles ur ON r.Id = ur.RoleId INNER JOIN Users u ON u.Id = ur.UserId WHERE u.UserName = @0";
                }
                return name;
            }
        }

        /// <summary>
        /// Gets a Role Record 
        /// </summary>
        /// <param name="roleName">The Role name</param>
        /// <returns>The Role Record </returns>
        public Role SelectByName(string roleName)
        {
            Role record = null;
            record = base.SelectByFieldValue("Name", roleName);
            return record;
        }

        /// <summary>
        /// Gets all the Role Records related with a User of a given name
        /// </summary>
        /// <param name="userName">The name of the User</param>
        /// <returns></returns>
        public List<Role> SelectRolesByUserName(string userName)
        {
            List<Role> list = null;
            list = Database.SelectList<Role>(SQLSelectRolesByUserName, userName);
            return list;
        }
    }
}